package edu.zjut.hjg.saas.web.interceptor;

import static edu.zjut.hjg.saas.web.support.SaaSConstants.SESSION_NAME_TENANT;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 租户权限拦截器
 * 
 * @author hjg
 */
public class TenantPermissionInterceptor extends HandlerInterceptorAdapter {

    private static final String ENCODE     = "UTF-8";
    private static final String LOGIN_PAGE = "/login/index.htm";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        if (request.getAttribute(SESSION_NAME_TENANT) != null) {
            // 已登录
            return true;
        }
        // 未登录
        String toUrl = getEncodedTargetUrl(request);
        response.sendRedirect(LOGIN_PAGE + "?toUrl=" + toUrl);
        return false;
    }

    private String getEncodedTargetUrl(HttpServletRequest request) {
        StringBuffer buff = request.getRequestURL();
        String queryString = request.getQueryString();
        if (queryString != null) {
            buff.append("?" + queryString);
        }
        try {
            return URLEncoder.encode(buff.toString(), ENCODE);
        } catch (UnsupportedEncodingException e) {
            return buff.toString();
        }
    }
}
